package cn.hg.solon.youcan.common.util;

import org.dromara.hutool.core.net.Ipv4Util;
import org.dromara.hutool.core.net.Ipv6Util;
import org.dromara.hutool.core.net.url.UrlBuilder;
import org.dromara.hutool.core.text.CharSequenceUtil;
import org.dromara.hutool.core.text.StrValidator;
import org.dromara.hutool.core.util.CharsetUtil;
import org.dromara.hutool.http.HttpUtil;
import org.dromara.hutool.json.JSONObject;
import org.dromara.hutool.json.JSONUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * 获取地址类
 * 
 * @author ruoyi
 */
public class AddressUtil {
    private static final Logger log = LoggerFactory.getLogger(AddressUtil.class);

    // IP地址查询
    public static final String IP_URL = "https://ip.cn/api/index";

    // 未知地址
    public static final String UNKNOWN = "XX XX";

    public static final String INNER_IPV6 = "0:0:0:0:0:0:0:1";

    public static final String INNER_IP = "内网IP";

    public static String getRealAddressByIP(String ip) {
        try {
            // 内网不查询
            if (CharSequenceUtil.equals(INNER_IPV6, ip)) {
                return INNER_IP;
            }

            // 内网不查询
            if (Ipv4Util.isInnerIP(ip)) {
                return INNER_IP;
            }
        } catch (Throwable e) {
            return Ipv6Util.getLocalMacAddress();
        }

        String rspStr = null;
        try {
            log.debug("获取地理位置：ip={}", ip);
            rspStr = HttpUtil.get(UrlBuilder.of(IP_URL).addQuery("ip", ip).addQuery("type", 1).toString(),
                CharsetUtil.UTF_8);
            if (StrValidator.isBlank(rspStr)) {
                log.error("获取地理位置异常 {}", ip);
                return UNKNOWN;
            }
            JSONObject obj = JSONUtil.parseObj(rspStr);
            return obj.getStr("address");
        } catch (Exception e) {
            log.error("获取地理位置异常：responseString={}, e={}", rspStr, e.getMessage(), e);
        }

        return UNKNOWN;
    }
}
